package com.solution;

/**
 * 19. 删除链表的倒数第 N 个结点
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 进阶：你能尝试使用一趟扫描实现吗？
 *
 * @author LiYongKui
 * @version 1.0
 * @date 2021/1/26 10:48
 */
public class Solution0019 {

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int len = getLength(head);
        if(n > len || n == 0){
            return head;
        }
        ListNode result = new ListNode(0,head);
        ListNode tmp = result;
        for (int i = 1; i < (len - n + 1); i++) {
            tmp = tmp.next;
        }
        tmp.next = tmp.next.next;

        return result.next;
    }

    public static int getLength(ListNode head){
        int result = 1;
        while (head.next != null){
            result++;
            head = head.next;
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5))));
        removeNthFromEnd(listNode,2);
    }

}

